package com.baitengsoft.patentapimonitor.api.service.impl;

import com.baitengsoft.patentapimonitor.api.dao.CfgPatentIndicatorDao;
import com.baitengsoft.patentapimonitor.api.dao.PacApplicantDao;
import com.baitengsoft.patentapimonitor.api.dao.WebPlatFormAreaDao;
import com.baitengsoft.patentapimonitor.api.entity.CfgDictionaryEntity;
import com.baitengsoft.patentapimonitor.api.entity.CfgPatentIndicatorEntity;
import com.baitengsoft.patentapimonitor.api.entity.WebPlatformareaEntity;
import com.baitengsoft.patentapimonitor.api.model.CfgPatentIndicatorInfo;
import com.baitengsoft.patentapimonitor.api.model.WebIndicatorInfo;
import com.baitengsoft.patentapimonitor.api.model.param.SearchPatentIndicatorParam;
import com.baitengsoft.patentapimonitor.api.service.CfgPatentIndicatorService;
import com.baitengsoft.patentapimonitor.common.utils.DateUtils;
import com.baitengsoft.patentapimonitor.common.utils.PageResult;
import com.baitengsoft.patentapimonitor.common.utils.Res;
import com.baitengsoft.patentapimonitor.common.utils.SearchParam;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 指标管理服务实现
 * @author Chen 2017/12/15
 */
@Service
public class CfgPatentIndicatorServiceImpl extends BaseServiceImpl<CfgPatentIndicatorEntity> implements CfgPatentIndicatorService{
    @Autowired
    private CfgPatentIndicatorDao cfgPatentIndicatorDaoDao;
    @Autowired
    private WebPlatFormAreaDao webPlatFormAreaDaoDao;


    /**
     * 获取专利指标汇总列表
     * @param searchParam
     * @return
     */
    @Override
    public PageResult<CfgPatentIndicatorInfo> getPatentIndicatorSum(SearchPatentIndicatorParam searchParam) {
        if(searchParam.getPlatformID() ==null){
            return null;
        }
        List<WebPlatformareaEntity> entities = webPlatFormAreaDaoDao.selectAreaByPlatformId(searchParam.getPlatformID());
        List<Integer> ids = new ArrayList<>();
        for (WebPlatformareaEntity entity : entities){
            Integer id = entity.getId();
            ids.add(id);
        }
        PageHelper.startPage(searchParam.getPageNumber(),searchParam.getPageSize());
        List<CfgPatentIndicatorInfo> infos = cfgPatentIndicatorDaoDao.getPatIndicatorSumByAreaIds(ids);
        return new PageResult<>(infos,searchParam.getPageNumber(),searchParam.getPageSize(),infos.size());
    }

    /**
     * 根据平台id查出特定年份的下属区域指标-数据
     * @param param
     * @return
     */
    @Override
    public PageResult<CfgPatentIndicatorInfo> getPatentIndicatorList(SearchPatentIndicatorParam param) {
        //获取平台下有效区域ID
        List<Integer> ids = webPlatFormAreaDaoDao.selectAreaIdByPlatFormId(param.getPlatformID());
        Page<Object> page = PageHelper.startPage(param.getPageNumber(), param.getPageSize());
        List<CfgPatentIndicatorInfo> infos = cfgPatentIndicatorDaoDao.getPatIndicatorByAreaAndYear(ids,param.getYear());
        Long total = page.getTotal();
        return new PageResult<>(infos,param.getPageNumber(),param.getPageSize(),total.intValue());
    }

    /**
     * 修改指标
     */
    @Override
    public Res updatePatentIndicator(List<CfgPatentIndicatorInfo> infos,Integer platfromId){
        List<WebPlatformareaEntity> entities = webPlatFormAreaDaoDao.selectAreaByPlatformId(platfromId);
        List<Integer> allids = new ArrayList<>();
        List<Integer> ids = new ArrayList<>();
        for (WebPlatformareaEntity entity : entities){
            Integer id = entity.getId();//区域id
            allids.add(id);

        }
        for(CfgPatentIndicatorInfo info :infos){
            Integer id = info.getId();//指标id
            CfgPatentIndicatorEntity entity = cfgPatentIndicatorDaoDao.selectByPrimaryKey(id);
            if (entity == null){
                return Res.error("未查询到该专利指标");
            }
            ids.add(entity.getAreaid());
        }
        if (!allids.containsAll(ids)){
            return Res.error("数据异常，无法修改");
        }
        for(CfgPatentIndicatorInfo info :infos){
            CfgPatentIndicatorEntity entity = cfgPatentIndicatorDaoDao.selectByPrimaryKey(info.getId());

            if(!entity.getDateym().equals(DateUtils.getCurrentYear())){
                return Res.error("无法修改历史年份");
            }
            entity.setId(info.getId());
            entity.setYxfmwrcount(info.getYxfmwrcount());
            entity.setPopulation(info.getPopulation());
            entity.setZlsqcount(info.getZlsqcount());
            entity.setFmsqcount(info.getFmsqcount());
            entity.setSqzlcount(info.getSqzlcount());
            entity.setSqzlfmcount(info.getSqzlfmcount());
            entity.setSqzlwrcount(info.getSqzlwrcount());
            entity.setSqzlfmwrcount(info.getSqzlfmwrcount());
            entity.setYxzlwrcount(info.getYxzlwrcount());
            entity.setYxzlcount(info.getYxzlcount());
            entity.setSzsccount(info.getSzsccount());
            entity.setYxfmcount(info.getYxfmcount());
            cfgPatentIndicatorDaoDao.updateByPrimaryKey(entity);
        }
        return Res.ok("保存成功！");
    }

    /**
     * 根据区域Id获取指定指标数值
     */
    @Override
    public CfgPatentIndicatorEntity getPatentIndicatorByAreaId(Integer areaId){
        CfgPatentIndicatorEntity entity = new CfgPatentIndicatorEntity();
        CfgPatentIndicatorEntity entity1;
        entity.setAreaid(areaId);
        try {
            entity1 = cfgPatentIndicatorDaoDao.selectOne(entity);
        }catch (Exception e){
            return null;
        }
        return entity1;
    }

    /**
     * 根据平台ID和年份获取该平台人口总和
     */
    @Override
    public BigDecimal getPopulationByPlatAndYear(Integer platformid, Integer currentYear) {
        if (platformid == null || platformid<1) return new BigDecimal(0);
        if (currentYear == null) return new BigDecimal(0);
        List<Integer> areaIds = webPlatFormAreaDaoDao.selectAreaIdByPlatFormId(platformid);
        return cfgPatentIndicatorDaoDao.getPopulationByPlatAndYear(areaIds,currentYear);
    }

    /***
     * 判断平台是否设置今年指标，
     * 都为0 返回false，
     * null自动生成为0 并返回false
     */
    @Override
    public boolean checkHasIndicatorByPlatormId(Integer platformid) {
        //根据平台ID查询区域ID
        List<Integer> ids = webPlatFormAreaDaoDao.selectAreaIdByPlatFormId(platformid);
        Example example = new Example(CfgPatentIndicatorEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("dateym",DateUtils.getCurrentYear());
        criteria.andIn("areaid",ids);
        List<CfgPatentIndicatorEntity> entities = cfgPatentIndicatorDaoDao.selectByExample(example);
        if (entities == null|| entities.size()<1){
            //初始化今年指标数据
            initIndicator(platformid);
            return false;
        }
        //该年所有指标数据之和是否等于0
        return !(cfgPatentIndicatorDaoDao.getAllIndicatorSum(ids, DateUtils.getCurrentYear()) == 0);
    }

    @Override
    public void deleteByAreaIdAndYearYM(Integer id, Integer currentYear) {
        cfgPatentIndicatorDaoDao.deleteByAreaIdAndYearYM(id,currentYear);
    }

    /**
     * 根据年份和区域ID初始化指标数据
     */
    @Override
    public void initIndicatorByAreaIdAndDateYM(Integer id, Integer currentYear) {
        cfgPatentIndicatorDaoDao.initIndicatorByAreaIdAndDateYM(id,currentYear);
    }

    private void initIndicator(Integer platformid){
        List<Integer> areaIds = webPlatFormAreaDaoDao.selectAreaIdByPlatFormId(platformid);
        Example example = new Example(CfgPatentIndicatorEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("dateym",DateUtils.getCurrentYear());
        criteria.andIn("areaid",areaIds);
        cfgPatentIndicatorDaoDao.deleteByExample(example);
        List<CfgPatentIndicatorEntity> entities = new ArrayList<>();
        for (Integer id : areaIds){
            CfgPatentIndicatorEntity entity = new CfgPatentIndicatorEntity();
            entity.setDateym(DateUtils.getCurrentYear());
            entity.setAreaid(id);
            entity.setCreateoperid(1);
            entity.setUpdateoperid(1);
            entity.setPopulation(BigDecimal.ZERO);
            entity.setYxfmcount(0);
            entity.setYxfmwrcount(BigDecimal.ZERO);
            entity.setYxzlcount(0);
            entity.setYxzlwrcount(BigDecimal.ZERO);
            entity.setZlsqcount(0);
            entity.setFmsqcount(0);
            entity.setSqzlcount(0);
            entity.setSqzlwrcount(0);
            entity.setSqzlfmcount(0);
            entity.setSqzlfmwrcount(0);
            entity.setSzsccount(0);
            entity.setCreatedate(new Date());
            entity.setUpdatedate(new Date());
            entities.add(entity);
        }
        int i = cfgPatentIndicatorDaoDao.insertList(entities);
    }
}
